//这里主要放一次性赋值完就不用了的函数
import { lib, game, ui, get, ai, _status } from '../../../noname.js'
export const swFunc = {
	vcardx(item, type, position, noclick, node) {
		const card = ui.create.buttonPresets.vcard(item, type, position, noclick, node)
		card.refresh = function (item) {
			if (!_status.skillMap[item]) {
				if (item.includes("_")) {
					const index = item.indexOf("_")
					item = item.slice(0, index)
				}
				if (!_status.skillMap[item]) return;
			}
			const character = _status.skillMap[item]
			this.node.name.innerHTML = `<div class="name" data-nature=${get.groupnature(get.character(character)[1], "raw")}m style="position: relative;color:#ffffff;fontweight:bold">${get.translation(item)}</div>`;
			this.setBackground(character, "character");
		}
		card.refresh(item)
		if (!lib.skillReplace[lib.translate[item]] || lib.skillReplace[lib.translate[item]].length < 2) return card
		const id = lib.skillReplace[lib.translate[item]].indexOf(item)
		const intro = ui.create.div(".button.replaceButton", `切换-${id + 1}`, card);
		intro.style.zIndex = '1000'
		intro._node = card
		intro[lib.experimental.symbol.itemType] = "button";
		card.node.replaceButton = intro
		intro.addEventListener(lib.config.touchscreen ? "touchend" : "click", function () {
			_status.tempNoButton = true;
			const node = this._node;
			const list = lib.skillReplace[lib.translate[node.name]];
			let link = node.name;
			let index = list.indexOf(link);
			if (index == list.length - 1) index = 0;
			else index++;
			link = list[index];
			node.node.replaceButton.innerHTML = `切换-${index + 1}`
			node.name = link
			node.link = node.link.slice();
			node.link[2] = link
			node.refresh(link);
			setTimeout(function () {
				delete _status.tempNoButton;
			}, 200);
		})
		return card
	},
	roomInfo() {
		var chat = ui.create.system(
			game.online ? "房间信息" : "房间设置",
			function () {
				if (!game.online || game.onlinezhu) {
					ui.click.connectMenu();
				}
			},
			true
		);
		ui.roomInfo = chat;
		lib.setPopped(
			chat,
			function () {
				if (game.getRoomInfo) {
					var uiintro = ui.create.dialog("hidden");

					//var list = ui.create.div(".caption");
					//lib.config.touchscreen ? "touchend" : "click"
					//var node = ui.create.div();
					//uiintro.appendChild(node);
					//node.innerHTML = "一键复制";

					var td = ui.create.div(".menubutton.reduce_radius.pointerdiv.tdnode");
					td.css({
						top: '8px',
					})
					var click = function () {
						if (confirm("该操作会复制该模式下的房间禁将，覆盖你的，是否继续？")) {
							game.saveConfig(`connect_${lib.configOL.mode}_banned`, lib.configOL.banned)
							alert("操作成功！")
						}
					}
					//td.link = listi[i];
					uiintro.add(td);
					td.innerHTML = "<span>复制房间禁将</span>";
					td.addEventListener(lib.config.touchscreen ? "touchend" : "click", click);

					game.getRoomInfo(uiintro);
					return uiintro;
				}
			},
			180
		);
	},
	_oldidentityList: get.identityList,
	identityList(numOfPlayers) {
		const list = swFunc._oldidentityList.call(this, numOfPlayers)
		if (lib.configOL.identity_neiReplaceZhong) {
			list.remove('nei')
			list.push('zhong')
		}
		if (numOfPlayers == 2) {
			list.remove('zhong')
			list.remove('nei')
		}
		return list
	},
	//可以使用样式的modetrans
	modetrans(config, server) {
		if (config.mode == "doudizhu") {
			switch (config.doudizhu_mode) {
				case "kaihei":
					return "开黑斗地主";
				case "huanle":
					return "欢乐斗地主";
				case "binglin":
					return "兵临城下";
				case "online":
					return "智斗三国";
				default:
					return "休闲" + (config.double_character ? "双将" : "") + "斗地主";
			}
		}
		if (config.mode == "versus") {
			switch (config.versus_mode) {
				case "1v1":
					return "单人对决";
				case "2v2":
					return "欢乐成双";
				case "3v3":
					return "血战到底";
				case "4v4":
					return "四人对决";
				case "guandu":
					return "官渡之战";
			}
		}
		if (config.mode == "single") {
			switch (config.single_mode) {
				case "normal":
					return "新１ｖ１";
				case "changban":
					return "血战长坂坡";
				case "dianjiang":
					return "点将单挑";
				case "wuxianhuoli":
					return "无限火力";
			}
		}
		if (config.mode == "identity") {
			switch (config.identity_mode) {
				case "purple":
					return "三对三对二";
				case "zhong":
					return (config.double_character ? "双将" : "") + "忠胆英杰";
				case "stratagem":
					return get.cnNumber(parseInt(config.number)) + "人" + (config.double_character ? "双将" : "") + "谋攻";
				default:
					return `${get.cnNumber(parseInt(config.number))}人${config.double_nei ? "双内" : ""}${config.enable_commoner ? "带民" : ""}${config.double_character ? "双将" : ""}身份`;
			}
		}
		if (config.mode == "guozhan") {
			if (config.separatism) return "群雄割据";
			if (config.guozhan_mode != "normal")
				switch (config.guozhan_mode) {
					case "yingbian":
						return "应变国战";
					case "old":
						return "怀旧国战";
				}
		}
		let modename = config.mode;
		let match = "";
		if(modename.includes("sw_infoText")) match = `<span class="sw_infoText">`
		else {
			const temp = modename.match(/style=["'][^"']*color:\s*([^;"']+)/i);
			match = `<span style="color: ${temp ? temp[1] : null};">`
		}
		modename = match + get.plainText(modename) + `</span>`;
		if (server) {
			return get.translation(modename) + "模式";
		} else {
			return get.cnNumber(parseInt(config.number)) + "人" + get.translation(modename);
		}
	},
	//客机的申请入场
	observeEnter()  {
		if (!ui.observeEnter2) {
			ui.observeEnter2 = ui.create.system("申请入场", null, true, true);
		}
		if(!_status.sw_html2) {
			_status.sw_html2 = true
			const style = document.createElement('style')
			style.innerHTML = swTool.observeEnterHTML
			document.head.appendChild(style)
		}
		var hoverpopped = async function() {
			if (this._uiintro) {
				return;
			}
			if (!this._poppedfunc) {
				return;
			}
			//ui.click.touchpop(this.forceclick);
			var uiintro = await this._poppedfunc();
			if (!uiintro) return;
			if (ui.currentpopped && ui.currentpopped._uiintro) {
				ui.currentpopped._uiintro.delete();
				delete ui.currentpopped._uiintro;
			}
			ui.currentpopped = this;
			uiintro.classList.add("popped");
			uiintro.classList.add("hoverdialog");
			uiintro.classList.add("static");
			this._uiintro = uiintro;

			ui.window.appendChild(uiintro);
			var width = this._poppedwidth || 330;
			uiintro.style.width = width + "px";
			if (get.is.phoneLayout()) {
				width *= 1.3;
			}

			if (uiintro._heightfixed) {
				uiintro.style.height = uiintro.content.scrollHeight + "px";
			} else {
				var height = this._poppedheight || uiintro.content.scrollHeight;
				var height2 = ui.window.offsetHeight - 260;
				if (get.is.phoneLayout()) {
					height2 = (ui.window.offsetHeight - 80) / 1.3;
				}
				uiintro.style.height = Math.min(height2, height) + "px";
			}
			if (get.is.phoneLayout()) {
				uiintro.style.top = "70px";
			} else {
				uiintro.style.top = "50px";
			}
			var left = this.parentNode.offsetLeft + this.offsetLeft + this.offsetWidth / 2 - width / 2;
			if (left < 10) {
				left = 10;
			} else if (left + width > ui.window.offsetWidth - 10) {
				left = ui.window.offsetWidth - width - 10;
			}
			uiintro.style.left = left + "px";
			uiintro._poppedorigin = this;
			if (!lib.config.touchscreen) {
				uiintro.addEventListener("mouseleave", ui.click.leavehoverpopped);
			}
			ui.click.shortcut(false);
			if (uiintro._onopen) {
				uiintro._onopen();
			}
		}
		ui.observeEnter2._poppedfunc = async function () {
			var uiintro = ui.create.dialog("hidden");

			uiintro.add("申请入场");
			uiintro.add('<div class="text center">滑动时请确保不要按住申请按钮滑动，否则可能会误触。</div>');
			uiintro.add('<div class="text center">每次旁观只有一次申请机会</div>');
			var table = ui.create.div(".observeContainer");

			//向服务器异步请求数据
			function getResult() {
				return new Promise((resolve, reject) => {
					try {
						// game.ws.send(JSON.stringify(['getObserveEnterPer']));
						// game.ws.addEventListener('message', function (e) {
						// 	//console.log(e.data)
						// 	let data = JSON.parse(JSON.parse(e.data)[0]);
						// 	if (data.type == 'getObserveEnterPer') {
						// 		resolve(data.data);
						// 	}
						// }, { once: true });
						const handler = function (e) {
							try {
								const raw = JSON.parse(e.data);
								if (Array.isArray(raw) && typeof raw[0] === 'string') {
									let data;
									try {
										data = JSON.parse(raw[0]);
									} catch {
										return;
									}
									if (data.type === 'getObserveEnterPer') {
										game.ws.removeEventListener('message', handler);
										resolve(data.data);
									}
								}
							} catch (err) {
								console.error('数据解析失败:', err, e.data);
								game.ws.removeEventListener('message', handler);
								resolve(false);
							}
						};

						game.ws.addEventListener("message", handler);
						game.ws.send(JSON.stringify(["getObserveEnterPer"]));

					} catch (error) {
						resolve(false);
					}
				});
			}

			let result = await getResult();
			if (!result) return;

			function click(item, player) {
				return function (e) {
					e.stopPropagation();
					e.preventDefault();
					if(_status.sw_requestObserveEntering) {
						alert("你有待同意的申请，请勿重复发送。本次观战只能发送一次申请。")
						return
					}
					if(item.textContent == "点击申请") {
						item.textContent = "正在申请..."
						_status.sw_requestObserveEntering = true
						item.classList.remove('canEnter');
						item.classList.add('forbidEnter');
						game.ws.send(JSON.stringify(["observeRequestEnter", lib?.config?.connect_nickname || "[未知玩家]", game.wsid, player.playerid]))
					}
				}
			}

			var player, added = false;
			for (var i = 0; i < game.players.length; i++) {
				added = true;
				let item = ui.create.div(".item", table);

				let avatar = ui.create.div(".avatar", item);
				avatar.style.backgroundImage = game.players[i].node.avatar.style.backgroundImage;
				let avatarName = ui.create.div(".avatarName", avatar);
				avatarName.textContent = game.players[i].nickname || "[电脑]";
				let avatarButton = ui.create.div(".avatarButton", avatar);

				let yeah = result[game.players[i].playerid]
				if(yeah) {
					avatarButton.textContent = "点击申请"
					avatarButton.classList.remove('forbidEnter');
					avatarButton.classList.add('canEnter');
				}
				else {
					avatarButton.textContent = "无权申请"
					avatarButton.classList.remove('canEnter');
					avatarButton.classList.add('forbidEnter');
				}
				avatarButton.addEventListener(lib.config.touchscreen ? "touchend" : "click", click(avatarButton, game.players[i]));
			}
			uiintro.add(table);

			return uiintro;
		};
		ui.observeEnter2._poppedwidth = 480;
		if (lib.config.touchscreen) {
			ui.observeEnter2.listen(hoverpopped);
		} else {
			ui.observeEnter2.addEventListener("mouseenter", hoverpopped);
		}
	},
	createDanMu(prefix = '', name = "[电脑玩家]", str = '') {
		if (!ui.danmuList) ui.danmuList = []
		if (!ui.bulletScreen) {
			ui.bulletScreen = ui.create.div('.bulletScreen', document.body)
			ui.bulletScreen.css({ width: "100%", height: "100%", left: "0", top: "0", pointerEvents: "none", zIndex: "100" })
		}
		let top = document.body.clientHeight / 3
		name = get.plainText(name)
		if (!swTool.isEmotion(str)) {
			str = get.plainText(str)
		}
		str = str.replace(/##assetURL##/g, lib.assetURL);
		if(name == "提示") {
			name = `<span style="color:yellow;">提示`
			str += `</span>`
		}
		const color = new Map([
			["r", "fire"],
			["y", "yellow"],
			["g", "green"],
			["b", "blue"],
		]);
		const strList = str.split("#")
		let newStr = "";
		strList.forEach((seg, index) => {
			if (index === 0) {
				newStr += seg;
			} else {
				newStr += `<span class="${color.get(seg[0]) || ""}text">${ seg.slice(1) }</span>`;
			}
		});
		const danmu = ui.create.div('.danmumode', `${prefix}${name}：${newStr}`, ui.bulletScreen)
		danmu.css({
			left: '100%',
			transition: 'left 18s cubic-bezier(0.45, 0.44, 0.55, 0.52) 0s',
			fontSize: "18px",
			textShadow: "1px 1px black",
			whiteSpace: "nowrap",
			fontFamily: "宋体",
			zIndex: "1000",
			pointerEvents: "none"
		})
		const { height } = danmu.getBoundingClientRect()
		let retry = 0
		while (ui.danmuList.includes(top)) {
			top += height
			if (top > document.body.clientHeight * 2 / 3) {
				top = 149 - height
				retry++
				if(retry >= 2) {
					ui.danmuList = []
					top = document.body.clientHeight / 3
				}
			}
		}
		ui.danmuList.add(top)
		danmu.style.top = top + "px"
		ui.refresh(danmu)
		danmu.style.left = "-10%"
		danmu.topBound = top
		const removeNode = function () {
			this.remove()
			ui.danmuList.remove(this.topBound)
		}
		danmu.addEventListener('transitionend', removeNode)
		danmu.addEventListener('webkittransitionend', removeNode)
	},
	// TODO：改为可以广播并且异步等待延迟
	playSkillVideo(name, time = 3000) {
		time += 300;
		let nowVideo = Array.from({ length: 25 }, (_, i) => `${lib.assetURL}extension/${swTool.extensionName}/assets/animation/border/${i}.png`);
		const cycleVideo = Array.from({ length: 25 }, (_, i) => `${lib.assetURL}extension/${swTool.extensionName}/assets/animation/border/${i + 25}.png`);
		if (!ui.skillVideo) {
			ui.skillVideo = ui.create.div("", ui.window, {
				position: "relative",
				zIndex: "100",
				width: "100%",
				height: "auto",
				aspectRatio: "667/205",
				top: "50%",
				transform: "translate(0%, -50%)",
				pointerEvents: "none",
			});
		}
		let currentFrame = 0;
		const img = document.createElement('img');
		img.style.width = "100%";
		img.style.height = "100%";
		img.style.zIndex = "10";
		img.style.position = "absolute";
		img.style.pointerEvents = "none";
		img.style.opacity = "0";
		img.src = nowVideo[currentFrame];
		ui.skillVideo.appendChild(img);

		const videoDiv = ui.create.div('', ui.skillVideo, {
			overflow: "hidden",
			width: "100%",
			height: "90%",
			top: "52%",
			transform: "translate(0%, -50%)",
			pointerEvents: "none",
			display:"flex",
			justifyContent: "center",
			alignItems: "center",
			opacity: 1,
			transition: "opacity 0.3s ease",
		})
		let finishReload = false;
		const video = document.createElement('video');
		video.src = `extension/${swTool.extensionName}/assets/animation/vedio/${name}.mp4`;
		video.controls = false;
		video.autoplay = true;
		video.style.width = '100%';
		video.style.height = 'auto';
		video.style.objectFit = 'cover';
		video.style.position = "absolute";
		video.style.opacity = "1";
		video.style.muted = true;
		video.playsInline = true;
		video.style.opacity = "0";
		video.style.transition = "opacity 0.3s ease";
		video.addEventListener('canplay', () => {
			video.style.opacity = "1";
			img.style.opacity = "1";
			finishReload = true;
		});
		// 调试事件
		video.onerror = (e) => console.error('视频加载失败', e);
		videoDiv.appendChild(video);

		const intervalId = setInterval(() => {
			if(!finishReload) return;
			currentFrame = (currentFrame + 1) % nowVideo.length;
			if(currentFrame === 0) nowVideo = cycleVideo;
			img.src = nowVideo[currentFrame];
		}, 33);

		const callback = () => {
			img.style.opacity = "0";
			videoDiv.style.opacity = "0";
			setTimeout(() => {
				clearInterval(intervalId);
				img.remove();
				videoDiv.remove();
			}, 300)
		}
		const intervalId2 = setTimeout(callback, time - 300);
		video.addEventListener('ended', () => {
			clearInterval(intervalId2);
			callback();
		});
	},
}
